(function() {
    
    var translation = {
        'Username has already been taken': '用户名已经有人使用',
        "Only use letters, numbers and '_'": '只能使用英文字母、数字及下划线',
        'Email has already been taken.': '邮箱已经有人使用',
		'Too short': '密码长度不够',
		'Too obvious': '密码过于简单',
		'Weak': '强度：弱',
		'Good': '强度：好',
		'String': '强度：强',
		'Very Strong': '强度：非常强'
    }
	
	var _ = function(str) {
		return translation[str];
	}
	
	function D(L, O) {
		var K = "";
		for (var N = 0; N < O.length; N++) {
			var P = true;
			for (var M = 0; M < L && (M + N + L) < O.length; M++) {
				P = P && (O.charAt(M + N) == O.charAt(M + N + L))
			}
			if (M < L) {
				P = false
			}
			if (P) {
				N += L - 1;
				P = false
			} else {
				K += O.charAt(N)
			}
		}
		return K
	}
	
	function I(K) {
		var M = 0;
		B = {};
		var L = B.minlength ? B.minlength : 6;
		if (K.length < L) {
			return {
				score: K.length,
				message: _("Too short"),
				className: "password-invalid"
			}
		}
		if (B.username) {
			var N = (typeof(B.username) == "function") ? B.username() : B.username;
			if (N && (K.toLowerCase() == N.toLowerCase())) {
				return {
					score: 0,
					message: _("Too obvious"),
					className: "password-invalid"
				}
			}
		}
		/*
		if ($.inArray(K.toLowerCase(), twttr.BANNED_PASSWORDS) != -1) {
			return {
				score: 0,
				message: _("Too obvious"),
				className: "password-invalid"
			}
		}
		*/
		M += K.length * 4;
		M += (D(1, K).length - K.length) * 1;
		M += (D(2, K).length - K.length) * 1;
		M += (D(3, K).length - K.length) * 1;
		M += (D(4, K).length - K.length) * 1;
		if (K.match(/(.*[0-9].*[0-9].*[0-9])/)) {
			M += 5
		}
		if (K.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) {
			M += 5
		}
		if (K.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
			M += 10
		}
		if (K.match(/([a-zA-Z])/) && K.match(/([0-9])/)) {
			M += 15
		}
		if (K.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && K.match(/([0-9])/)) {
			M += 15
		}
		if (K.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && K.match(/([a-zA-Z])/)) {
			M += 15
		}
		if (K.match(/^\w+$/) || K.match(/^\d+$/)) {
			M -= 10
		}
		if (M < 0) {
			M = 0
		}
		if (M > 100) {
			M = 100
		}
		if (M < 34) {
			return {
				score: M,
				message: _("Weak"),
				className: "password-weak"
			}
		}
		if (M < 50) {
			return {
				score: M,
				message: _("Good"),
				className: "password-good"
			}
		}
		if (M < 75) {
			return {
				score: M,
				message: _("Strong"),
				className: "password-strong"
			}
		}
		return {
			score: M,
			message: _("Very Strong"),
			className: "password-verystrong"
		}
	}
	
	var setStatus = function(textbox, status) {
		return textbox.parent().find('span').html(status);
	}

    var err = function(textbox, msg) {
		setStatus(textbox, msg).addClass('error');
        // textbox.parent().find('span').addClass('error').html(msg);
    }
    
    var ok = function(textbox) {
        //extbox.parent().find('span').removeClass('error').html('<img src="img/check.gif" alt="ok" />');
		setStatus(textbox, '<img src="img/check.gif" alt="ok" />').removeClass('error');
    }

    var loading = function(textbox) {
        //textbox.parent().find('span').removeClass('error').html('<img src="img/indicator.gif" alt="loading" />');
		setStatus(textbox, '<img src="img/indicator.gif" alt="loading" />').removeClass('error');
    }
    
    var reEmpty = /^\s*$/;
    var reEmail = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;

    var urlencode = function(str) {
        return escape(str).replace('+', '%2B').replace('%20', '+').replace('*', '%2A').replace('/', '%2F').replace('@', '%40');
    }
    
    $('#user_name').blur(function() {
        var self = $(this);
        if (reEmpty.test(self.val())) {
            err(self, '姓名不能为空');
            return;
        }
        ok(self);
    });
    
    $('#user_screen_name').blur(function() {
        var self = $(this);
        if (reEmpty.test(self.val())) {
            err(self, '用户名不能为空');
            return;
        }
        loading(self);
        $.getJSON('available.php?t=username&v=' + escape(self.val()), function(data) {
            var span = self.parent().find('span');
            if (data.valid) {
                ok(self);
            } else {
                err(self, translation[data.msg] || data.msg);
            }
        });
    });

    $('#user_email').blur(function() {
        var self = $(this);
        var email = self.val();
        if (!reEmail.test(email)) {
            err(self, '输入的邮箱地址不合法');
            return;
        }
        if (reEmpty.test(email)) {
            err(self, '邮箱不能为空');
            return;
        }
        loading(self);
        $.getJSON('available.php?t=email&v=' + urlencode(email), function(data) {
            var span = self.parent().find('span');
            if (data.valid) {
                ok(self);
            } else {
                err(self, translation[data.msg] || data.msg);
            }
        });
    });
    
    $('#user_user_password').blur(function() {
        var self = $(this);
        // ok(self);
		
		var result = I(self.val());
		setStatus(self, result.message);
    });
	
	$('#user_user_password').keyup(function() {
		var self = $(this);
		var result = I(self.val());
		setStatus(self, result.message);
	});

    $('#refresh').click(function() {
        $.getJSON('auth.php', function(data) {
           $('#auth').val(data.auth);
           $('#challenge_field').val(data.challenge);
           $('#recaptcha_image').attr({
                src: 'image.php?c=' + data.challenge
            });
        });
    });

})();
